<?php

namespace app\index\controller;

use think\Db as resourceDB;
use think\Log;
use think\Cache;


class Resource extends Common{

    public $datas;

    /**
     * 查询新成果数量
     */
    public function getNewResourceNum(){
        /**
         * userId              名片编号
         */
        $this->datas = $this->params;

        $this->getNewResourceNumService();
    }


    private function getNewResourceNumService(){

        //查询名片信息
        $usersql = "select * from user where id = ".$this->datas['userId'];
        $userres = resourceDB::query($usersql);

        $userName = $userres[0]["user_name"];


        $sql = "SELECT COUNT(1) AS num FROM resource_collection c WHERE c.creator = '".$userName."' AND c.id NOT IN ( SELECT r.resource_id FROM user_resource r WHERE r.user_id = ".$this->datas['userId'].")";
        $res = resourceDB::query($sql);



        $this->returnMsg(1, '获取数据成功！',$res[0]["num"]);
    }

    /**
     * 成果补全
     */
    public function completeResource(){
        /**
         * userId              名片编号
         * email               邮箱
         * content             内容
         */
        $this->datas = $this->params;

        $this->completeResourceService();
    }


    private function completeResourceService(){

        $insertData = [];
        $insertData['user_id'] = $this->datas['userId'];
        $insertData['email'] = $this->datas['email'];
        $insertData['content'] = $this->datas['content'];
        $insertData['create_time'] = date('Y-m-d H:i:s');
        $insertData['update_time'] = date('Y-m-d H:i:s');
        $insertData['status'] = 1;

        resourceDB::table('send_email')->insert($insertData);


        $this->returnMsg(1, '操作成功！');
    }


     /**
     * 成果认领页面查询（成果数量-年）
     */
    public function getNewResourceNumByYear(){
        /**
         * userId              名片编号
         * year                最近多少年
         */
        $this->datas = $this->params;

        $this->getNewResourceNumByYearService();
    }


    private function getNewResourceNumByYearService(){
        //查询名片信息
        $userInfo = resourceDB::table('user')->where('id',$this->datas['userId'])->find();
        if(empty($userInfo)){
            $this->returnMsg(9, '名片信息有误！');
        }

        /*$res = array();
        $j=0;
        for($i=0; $i < $this->datas['year'];$i++){
            $UserEnameInfo = '';
            if(!empty($userInfo["e_user_name"]) and $userInfo["e_user_name"] != ''){
                $eUserInfo = json_decode($userInfo["e_user_name"],true);
                foreach ($eUserInfo as $k=>$v) {
                    $UserEnameInfo.= $v["name"]."|";
                }
                $UserEnameInfo = substr($UserEnameInfo,0,strlen($UserEnameInfo)-1);
            }

            $searchYear = date('Y', strtotime("-".$i." year"));
            
            $numsql = "SELECT COUNT(1) AS num FROM resource_collection c WHERE c.year = '".$searchYear."' AND c.id NOT IN ( SELECT r.resource_id FROM user_resource r WHERE r.user_id = ".$this->datas['userId'].")";
            //$numsql = $numsql." AND ((c.resourceCode IN ('D','J','P') and c.creatorAll LIKE '%".$userInfo["user_name"]."%'  and c.instituteAll LIKE '%".$userInfo["institute"]."%') OR (c.resourceCode IN ('E','I','U') AND c.creatorAlt LIKE '%".$userInfo["user_name"]."%' ) or (c.resourceCode IN ('A','B','C','O','Q','R','S','T','Y') AND c.creatorAll LIKE '%".$userInfo["user_name"]."%'))";
            $numsql = $numsql." AND ((c.resourceCode IN ('D','J','P') and c.creatorAll LIKE '%".$userInfo["user_name"]."%') OR (c.resourceCode IN ('E','I','U') AND c.creatorAll REGEXP '".$UserEnameInfo."' ) or (c.resourceCode IN ('A','B','C','O','Q','R','S','T','Y') AND c.creatorAll LIKE '%".$userInfo["user_name"]."%'))";

            $numres = resourceDB::query($numsql);
            if($numres[0]['num'] > 0){
                $oneres;
                $oneres["year"] = $searchYear;
                $oneres["resourceNum"] = $numres[0]['num'];
                $res[$j] = $oneres;
                $j ++;
            }
        }*/

        $yearEnd = date('Y');
        $yearBegin = $yearEnd - $this->datas['year'];
        $UserEnameInfo = '';
        if(!empty($userInfo["e_user_name"]) and $userInfo["e_user_name"] != ''){
            $eUserInfo = json_decode($userInfo["e_user_name"],true);
            foreach ($eUserInfo as $k=>$v) {
                $UserEnameInfo.= $v["name"]."|";
            }
            $UserEnameInfo = substr($UserEnameInfo,0,strlen($UserEnameInfo)-1);
        }

        $numsql = "SELECT c.year,COUNT(1) AS resourceNum FROM resource_collection c LEFT JOIN (SELECT r.resource_id FROM user_resource r WHERE r.user_id = ".$this->datas['userId']." ) r ";
        $numsql = $numsql."on c.id = r.resource_id WHERE c.year between '".$yearBegin."' and '".$yearEnd."'";
        $numsql = $numsql." AND ((c.resourceCode IN ('D','J','P') and c.creatorAll LIKE '%".$userInfo["user_name"]."%') OR (c.resourceCode IN ('E','I','U') AND c.creatorAll REGEXP '".$UserEnameInfo."' ) or (c.resourceCode IN ('A','B','C','O','Q','R','S','T','Y') AND c.creatorAll LIKE '%".$userInfo["user_name"]."%')) and r.resource_id is null GROUP BY c.`year` order by c.`year` desc ";
        $res = resourceDB::query($numsql);


        //更早年份
        $UserEnameInfo = '';
        if(!empty($userInfo["e_user_name"]) and $userInfo["e_user_name"] != ''){
            $eUserInfo = json_decode($userInfo["e_user_name"],true);
            foreach ($eUserInfo as $k=>$v) {
                $UserEnameInfo.= $v["name"]."|";
            }
            $UserEnameInfo = substr($UserEnameInfo,0,strlen($UserEnameInfo)-1);
        }

        $earlierYear = date('Y', strtotime("-".$this->datas['year']." year"));
        $earliersql = "SELECT COUNT(1) AS num FROM resource_collection c WHERE c.year <= '".$earlierYear."' AND c.id NOT IN ( SELECT r.resource_id FROM user_resource r WHERE r.user_id = ".$this->datas['userId'].")";
        //$earliersql = $earliersql." AND ((c.resourceCode IN ('D','J','P') and c.creatorAll LIKE '%".$userInfo["user_name"]."%'  and c.instituteAll LIKE '%".$userInfo["institute"]."%') OR (c.resourceCode IN ('E','I','U') AND c.creatorAlt LIKE '%".$userInfo["user_name"]."%' ) or (c.resourceCode IN ('A','B','C','O','Q','R','S','T','Y') AND c.creatorAll LIKE '%".$userInfo["user_name"]."%'))";
        $earliersql = $earliersql." AND ((c.resourceCode IN ('D','J','P') and c.creatorAll LIKE '%".$userInfo["user_name"]."%') OR (c.resourceCode IN ('E','I','U') AND c.creatorAll REGEXP '".$UserEnameInfo."' ) or (c.resourceCode IN ('A','B','C','O','Q','R','S','T','Y') AND c.creatorAll LIKE '%".$userInfo["user_name"]."%'))";

        /*$earliernumres = resourceDB::query($earliersql);
        if($earliernumres[0]['num'] > 0){
            $oneres;
            $oneres["year"] = $earlierYear.'+';
            $oneres["resourceNum"] = $earliernumres[0]['num'];
            $res[$j] = $oneres;
        }*/

        $this->returnMsg(1, '获取数据成功！',$res);
    }


    /**
     * 成果认领页面查询（成果数量-类型）
     */
    public function getNewResourceNumByType(){
        /**
         * userId              名片编号
         * year                年份（有加号表示更早）
         */
        $this->datas = $this->params;

        $this->getNewResourceNumByTypeService();
    }


    private function getNewResourceNumByTypeService(){
        //查询名片信息
        $userInfo = resourceDB::table('user')->where('id',$this->datas['userId'])->find();
        if(empty($userInfo)){
            $this->returnMsg(9, '名片信息有误！');
        }

        $numsql;

        $UserEnameInfo = '';
        if(!empty($userInfo["e_user_name"]) and $userInfo["e_user_name"] != ''){
            $eUserInfo = json_decode($userInfo["e_user_name"],true);
            foreach ($eUserInfo as $k=>$v) {
                $UserEnameInfo.= $v["name"]."|";
            }
            $UserEnameInfo = substr($UserEnameInfo,0,strlen($UserEnameInfo)-1);
        }

        if(!empty($this->datas['year']) and $this->datas['year'] != ''){
            if(strpos($this->datas['year'], '+') !== false){
                $searchYear = substr($this->datas['year'],0,4);
                $numsql = "SELECT c.resourceCode,COUNT(1) as num FROM resource_collection c ";
                $numsql = $numsql."left join (SELECT r.resource_id FROM user_resource r WHERE r.user_id = ".$this->datas['userId'].") d on c.id = d.resource_id ";
                //$numsql = $numsql." AND ((c.resourceCode IN ('D','J','P') and c.creatorAll LIKE '%".$userInfo["user_name"]."%'  and c.instituteAll LIKE '%".$userInfo["institute"]."%') OR (c.resourceCode IN ('E','I','U') AND c.creatorAlt LIKE '%".$userInfo["user_name"]."%' ) or (c.resourceCode IN ('A','B','C','O','Q','R','S','T','Y') AND c.creatorAll LIKE '%".$userInfo["user_name"]."%'))";
                $numsql = $numsql."WHERE c.year <= '".$searchYear."'  AND ((c.resourceCode IN ('D','J','P') and c.creatorAll LIKE '%".$userInfo["user_name"]."%') OR (c.resourceCode IN ('E','I','U') AND c.creatorAll REGEXP '".$UserEnameInfo."' ) or (c.resourceCode IN ('A','B','C','O','Q','R','S','T','Y') AND c.creatorAll LIKE '%".$userInfo["user_name"]."%'))";
                $numsql = $numsql."and d.resource_id is null";
                $numsql = $numsql." GROUP BY c.resourceCode ORDER BY c.resourceCode";
            }else{
                $searchYear = substr($this->datas['year'],0,4);
                $numsql = "SELECT c.resourceCode,COUNT(1) as num FROM resource_collection c ";
                $numsql = $numsql."left join (SELECT r.resource_id FROM user_resource r WHERE r.user_id = ".$this->datas['userId'].") d on c.id = d.resource_id ";
                //$numsql = $numsql." AND ((c.resourceCode IN ('D','J','P') and c.creatorAll LIKE '%".$userInfo["user_name"]."%'  and c.instituteAll LIKE '%".$userInfo["institute"]."%') OR (c.resourceCode IN ('E','I','U') AND c.creatorAlt LIKE '%".$userInfo["user_name"]."%' ) or (c.resourceCode IN ('A','B','C','O','Q','R','S','T','Y') AND c.creatorAll LIKE '%".$userInfo["user_name"]."%'))";
                $numsql = $numsql."WHERE c.year = '".$searchYear."' AND ((c.resourceCode IN ('D','J','P') and c.creatorAll LIKE '%".$userInfo["user_name"]."%') OR (c.resourceCode IN ('E','I','U') AND c.creatorAll REGEXP '".$UserEnameInfo."' ) or (c.resourceCode IN ('A','B','C','O','Q','R','S','T','Y') AND c.creatorAll LIKE '%".$userInfo["user_name"]."%'))";
                $numsql = $numsql."and d.resource_id is null";
                $numsql = $numsql." GROUP BY c.resourceCode ORDER BY c.resourceCode";
            }
        }else{
            $numsql = "SELECT c.resourceCode,COUNT(1) as num FROM resource_collection c ";
            $numsql = $numsql."left join (SELECT r.resource_id FROM user_resource r WHERE r.user_id = ".$this->datas['userId'].") d on c.id = d.resource_id ";
            //$numsql = $numsql." AND ((c.resourceCode IN ('D','J','P') and c.creatorAll LIKE '%".$userInfo["user_name"]."%'  and c.instituteAll LIKE '%".$userInfo["institute"]."%') OR (c.resourceCode IN ('E','I','U') AND c.creatorAlt LIKE '%".$userInfo["user_name"]."%' ) or (c.resourceCode IN ('A','B','C','O','Q','R','S','T','Y') AND c.creatorAll LIKE '%".$userInfo["user_name"]."%'))";
            $numsql = $numsql."where ((c.resourceCode IN ('D','J','P') and c.creatorAll LIKE '%".$userInfo["user_name"]."%' ) OR (c.resourceCode IN ('E','I','U') AND c.creatorAll REGEXP '".$UserEnameInfo."' ) or (c.resourceCode IN ('A','B','C','O','Q','R','S','T','Y') AND c.creatorAll LIKE '%".$userInfo["user_name"]."%'))";
            $numsql = $numsql."and d.resource_id is null";
            $numsql = $numsql." GROUP BY c.resourceCode ORDER BY c.resourceCode";
        }




        $numres = resourceDB::query($numsql);

        $this->returnMsg(1, '获取数据成功！',$numres);
    }


     /**
     * 成果认领页面查询（成果分页）
     */
    public function getNewResourceNumPage(){
        /**
         * userId              名片编号
         * type                查询类型（1-未查看成果，2-已查看成果，3-搜索成果）
         * year                年份（有加号表示更早）
         * resourceCode        资源类型简写
         * searchName          搜索名称
         * pageNo              页码
         * pageSize            每页条数
         */
        $this->datas = $this->params;

        $this->getNewResourceNumPageService();
    }


    private function getNewResourceNumPageService(){
        //查询名片信息
        $userInfo = resourceDB::table('user')->where('id',$this->datas['userId'])->find();
        if(empty($userInfo)){
            $this->returnMsg(9, '名片信息有误！');
        }

        $pageNo = 1;
        $pageSize = 10;

        if(!empty($this->datas['pageNo'])){
            $pageNo = $this->datas['pageNo'];
        }

        if(!empty($this->datas['pageSize'])){
            $pageSize = $this->datas['pageSize'];
        }

        $pageNo = ($pageNo - 1) * $pageSize;

        $sql = "SELECT c.id,c.title,c.creator,IFNULL(c.keyword,'') as keyword,IFNULL(c.institute,'') as institute,c.year,c.resourceCode,IFNULL(c.tag,'') as tag,url FROM resource_collection c WHERE c.id NOT IN ( SELECT r.resource_id FROM user_resource r WHERE r.user_id = ".$this->datas['userId'].")";

        $countsql = "SELECT COUNT(1) as num FROM resource_collection c WHERE c.id NOT IN ( SELECT r.resource_id FROM user_resource r WHERE r.user_id = ".$this->datas['userId'].")";

        if(!empty($this->datas['year']) and $this->datas['year'] != ''){
            if(strpos($this->datas['year'], '+') !== false){
                $searchYear = substr($this->datas['year'],0,4);

                $sql = $sql." and c.year <= '".$searchYear."'";
                $countsql = $countsql." and c.year <= '".$searchYear."'";
                
            }else{
                $searchYear = substr($this->datas['year'],0,4);
                $sql = $sql." and c.year = '".$searchYear."'";
                $countsql = $countsql." and c.year = '".$searchYear."'";
            }
        }

        if(!empty($this->datas['resourceCode']) and $this->datas['resourceCode'] != ''){
            $sql = $sql." and c.resourceCode = '".$this->datas['resourceCode']."'";
            $countsql = $countsql." and c.resourceCode = '".$this->datas['resourceCode']."'";
        }

        if(!empty($this->datas['searchName']) and $this->datas['searchName'] != ''){
            $sql = $sql." and c.title like '%".$this->datas['searchName']."%'";
            $countsql = $countsql." and c.title like '%".$this->datas['searchName']."%'";
        }

        if($this->datas['type'] == 1){
            $sql = $sql." and c.id not in (SELECT resource_id from user_search_resource WHERE user_id = ".$this->datas['userId'].") ";
            $countsql = $countsql." and c.id not in (SELECT resource_id from user_search_resource WHERE user_id = ".$this->datas['userId'].") ";

        }

        if($this->datas['type'] == 2){
            $sql = $sql." and c.id in (SELECT resource_id from user_search_resource WHERE user_id = ".$this->datas['userId'].") ";
            $countsql = $countsql." and c.id in (SELECT resource_id from user_search_resource WHERE user_id = ".$this->datas['userId'].") ";
        }

        if($this->datas['type'] == 1 || $this->datas['type'] == 2){
            $UserEnameInfo = '';
            if(!empty($userInfo["e_user_name"]) and $userInfo["e_user_name"] != ''){
                $eUserInfo = json_decode($userInfo["e_user_name"],true);
                foreach ($eUserInfo as $k=>$v) {
                    $UserEnameInfo.= $v["name"]."|";
                }
                $UserEnameInfo = substr($UserEnameInfo,0,strlen($UserEnameInfo)-1);
            }

            //$sql = $sql." AND ((c.resourceCode IN ('D','J','P') and c.creatorAll LIKE '%".$userInfo["user_name"]."%'  and c.instituteAll LIKE '%".$userInfo["institute"]."%') OR (c.resourceCode IN ('E','I','U') AND c.creatorAll REGEXP '".$UserEnameInfo."' ) or (c.resourceCode IN ('A','B','C','O','Q','R','S','T','Y') AND c.creatorAll LIKE '%".$userInfo["user_name"]."%'))";
            $sql = $sql." AND ((c.resourceCode IN ('D','J','P') and c.creatorAll LIKE '%".$userInfo["user_name"]."%') OR (c.resourceCode IN ('E','I','U') AND c.creatorAll REGEXP '".$UserEnameInfo."' ) or (c.resourceCode IN ('A','B','C','O','Q','R','S','T','Y') AND c.creatorAll LIKE '%".$userInfo["user_name"]."%'))";
            //$countsql = $countsql." AND ((c.resourceCode IN ('D','J','P') and c.creatorAll LIKE '%".$userInfo["user_name"]."%'  and c.instituteAll LIKE '%".$userInfo["institute"]."%') OR (c.resourceCode IN ('E','I','U') AND c.creatorAlt REGEXP '".$UserEnameInfo."' ) or (c.resourceCode IN ('A','B','C','O','Q','R','S','T','Y') AND c.creatorAll LIKE '%".$userInfo["user_name"]."%'))";
            $countsql = $countsql." AND ((c.resourceCode IN ('D','J','P') and c.creatorAll LIKE '%".$userInfo["user_name"]."%') OR (c.resourceCode IN ('E','I','U') AND c.creatorAlt REGEXP '".$UserEnameInfo."' ) or (c.resourceCode IN ('A','B','C','O','Q','R','S','T','Y') AND c.creatorAll LIKE '%".$userInfo["user_name"]."%'))";
        }

        $sql = $sql." ORDER BY c.year DESC,c.id limit ".$pageNo.",".$pageSize;

        $res = resourceDB::query($sql);
        $count = resourceDB::query($countsql);

        $this->returnMsg(1, '获取数据成功！', $res, $count[0]["num"]);
    }
	
	
	 /**
     * 成果标记为已查看
     */
    public function setResourceSearch(){
        /**
         * userId              名片编号
         * resourceId          资源编号
         */
        $this->datas = $this->params;

        $this->setResourceSearchService();
    }


    private function setResourceSearchService(){

        $insertSearchData = [];
		$insertSearchData['resource_id'] = $this->datas['resourceId'];
		$insertSearchData['user_id'] = $this->datas['userId'];
		$insertSearchData['create_time'] = date('Y-m-d H:i:s');
		resourceDB::table('user_search_resource')->insert($insertSearchData);

        $this->returnMsg(1, '操作成功！');
    }
	

     /**
     * 成果认领
     */
    public function addNewResource(){
        /**
         * userId              名片编号
         * resourceIdList      资源编号列表
         */
        $this->datas = $this->params;

        $this->addNewResourceService();
    }


    private function addNewResourceService(){
        
        $resourceIdArray = explode(',',$this->datas['resourceIdList']);
        foreach($resourceIdArray as $value){
            //查询该资源是否添加过
            $userResource = resourceDB::table('user_resource')->where('resource_id',$value)->where('user_id',$this->datas['userId'])->find();
            if(empty($userResource)){
                //查询资源信息
                $resourceCollection = resourceDB::table('resource_collection')->where('id',$value)->find();

                if(!empty($resourceCollection)){
                    //增加名片资源关联信息
                    $insertData = [];
                    $insertData['user_id'] = $this->datas['userId'];
                    $insertData['resource_id'] = $value;
                    $insertData['create_time'] = date('Y-m-d H:i:s');
                    $insertData['resource_code'] = $resourceCollection['resourceCode'];
                    $insertData['year'] = $resourceCollection['year'];
                    resourceDB::table('user_resource')->insert($insertData);

                    
                    //否保存在各个资源表中
                    //$this->insertResourceService($resourceCollection);

                    //保存资源集合表
                    $insertLocalhostSql = "INSERT IGNORE INTO local_resource_collection SELECT *,NOW() as claim_time FROM resource_collection WHERE id = '".$value."'";
                    resourceDB::execute($insertLocalhostSql);

                    // 添加用户名片操作记录
                    insert_user_log($this->datas['userId'], 3);

                }
            }
        }
        $this->returnMsg(1, '操作成功！');
    }



    private function insertResourceService($resourceCollection){
        //判断是否保存在各个资源表中
        //论文：D  I   E   J   U  C
        //成果奖励:A
        //专著:B
        //知识产权:P
        //科研项目:O
        
        switch ($resourceCollection['resourceCode']) {

            case "C":
                $this->insertResourceDissertationService($resourceCollection);
                break;
            case "D":
                $this->insertResourceDissertationService($resourceCollection);
                break;
            case "I":
                $this->insertResourceDissertationService($resourceCollection);
                break;
            case "E":
                $this->insertResourceDissertationService($resourceCollection);
                break;
            case "J":
                $this->insertResourceDissertationService($resourceCollection);
                break;
            case "U":
                $this->insertResourceDissertationService($resourceCollection);
                break;
            case "A":
                $this->insertResourceAchievementService($resourceCollection);
                break;
            case "B":
                $this->insertResourceBookService($resourceCollection);
                break;
            case "P":
                $this->insertResourceIntellectualService($resourceCollection);
                break;
            case "O":
                $this->insertResourceProjectService($resourceCollection);
                break;
            default:
                ;
        }
    }


    private function insertResourceDissertationService($resourceCollection){
        $resource = resourceDB::table('resource_dissertation')->where('id',$resourceCollection['id'])->find();
        if(empty($resource)){
            $insertData = [];
            $insertData['id'] = $resourceCollection['id'];
            $insertData['title'] = $resourceCollection['title'];
            $insertData['creator'] = $resourceCollection['creator'];
            $insertData['keyword'] = $resourceCollection['keyword'];
            $insertData['abstract'] = '???';
            $insertData['institute'] = $resourceCollection['institute'];
            $insertData['title_alt'] = $resourceCollection['titleAlt'];
            $insertData['keyword_alt'] = $resourceCollection['keywordAlt'];
            $insertData['abstract_alt'] = '???';
            $insertData['subject'] = $resourceCollection['subject'];
            $insertData['language'] = $resourceCollection['language'];
            $insertData['page'] = $resourceCollection['page'];
            $insertData['doi'] = $resourceCollection['doi'];
            $insertData['issn'] = $resourceCollection['issue'];
            $insertData['journal'] = $resourceCollection['journal'];
            $insertData['year'] = $resourceCollection['year'];
            $insertData['volume'] = $resourceCollection['volume'];
            $insertData['issue'] = $resourceCollection['issue'];
            $insertData['creator_all'] = $resourceCollection['creatorAll'];
            $insertData['url'] = $resourceCollection['url'];
            $insertData['is_core'] = $resourceCollection['isCore'];
            $insertData['institute_all'] = $resourceCollection['instituteAll'];
            $insertData['resource_code'] = $resourceCollection['resourceCode'];
            $insertData['source'] = $resourceCollection['source'];
            $insertData['tag'] = $resourceCollection['tag'];
            resourceDB::table('resource_dissertation')->insert($insertData);
        }

    }

    private function insertResourceAchievementService($resourceCollection){
        $resource = resourceDB::table('resource_achievement')->where('id',$resourceCollection['id'])->find();
        if(empty($resource)){
            $insertData = [];
            $insertData['id'] = $resourceCollection['id'];
            $insertData['title'] = $resourceCollection['title'];
            $insertData['creator'] = $resourceCollection['creator'];
            $insertData['keyword'] = $resourceCollection['keyword'];
            $insertData['abstract'] = '???';
            $insertData['institute'] = $resourceCollection['institute'];
            $insertData['year'] = $resourceCollection['year'];
            $insertData['type'] = '???';
            $insertData['subject'] = $resourceCollection['subject'];
            $insertData['province'] = $resourceCollection['province'];
            $insertData['city'] = '???';
            $insertData['language'] = $resourceCollection['language'];
            $insertData['resource_code'] = $resourceCollection['resourceCode'];
            $insertData['source'] = $resourceCollection['source'];
            $insertData['tag'] = $resourceCollection['tag'];
            resourceDB::table('resource_achievement')->insert($insertData);
        }

    }

    private function insertResourceBookService($resourceCollection){
        $resource = resourceDB::table('resource_book')->where('id',$resourceCollection['id'])->find();
        if(empty($resource)){
            $insertData = [];
            $insertData['id'] = $resourceCollection['id'];
            $insertData['title'] = $resourceCollection['title'];
            $insertData['creator'] = $resourceCollection['creator'];
            $insertData['abstract'] = '???';
            $insertData['publisher'] = $resourceCollection['publisher'];
            $insertData['subject'] = $resourceCollection['subject'];
            $insertData['language'] = $resourceCollection['language'];
            $insertData['year'] = $resourceCollection['year'];
            $insertData['isbn'] = $resourceCollection['isbn'];
            $insertData['resource_code'] = $resourceCollection['resourceCode'];
            $insertData['source'] = $resourceCollection['source'];
            $insertData['tag'] = $resourceCollection['tag'];
            resourceDB::table('resource_book')->insert($insertData);
        }

    }

    private function insertResourceIntellectualService($resourceCollection){
        $resource = resourceDB::table('resource_intellectual')->where('id',$resourceCollection['id'])->find();
        if(empty($resource)){
            $insertData = [];
            $insertData['id'] = $resourceCollection['id'];
            $insertData['title'] = $resourceCollection['title'];
            $insertData['patent_no'] = $resourceCollection['patentNo'];
            $insertData['owner'] = '???';
            $insertData['creator'] = $resourceCollection['creator'];
            $insertData['application_no'] = $resourceCollection['applicationNo'];
            $insertData['type'] = '???';
            $insertData['url'] = $resourceCollection['url'];
            $insertData['address'] = $resourceCollection['address'];
            $insertData['abstract'] = '???';
            $insertData['domain'] = $resourceCollection['domain'];
            $insertData['application_date'] = $resourceCollection['applicationDate'];
            $insertData['publication_date'] = $resourceCollection['publicationDate'];
            $insertData['language'] = $resourceCollection['language'];
            $insertData['resource_code'] = $resourceCollection['resourceCode'];
            $insertData['source'] = $resourceCollection['source'];
            $insertData['tag'] = $resourceCollection['tag'];
            resourceDB::table('resource_intellectual')->insert($insertData);
        }

    }

    private function insertResourceProjectService($resourceCollection){
        $resource = resourceDB::table('resource_project')->where('id',$resourceCollection['id'])->find();
        if(empty($resource)){
            $insertData = [];
            $insertData['id'] = $resourceCollection['id'];
            $insertData['title'] = $resourceCollection['title'];
            $insertData['creator'] = $resourceCollection['creator'];
            $insertData['keyword'] = $resourceCollection['keyword'];
            $insertData['abstract'] = '???';
            $insertData['institute'] = $resourceCollection['institute'];
            $insertData['projectid'] = $resourceCollection['projectNo'];
            $insertData['projectFund'] = $resourceCollection['projectFund'];
            $insertData['projectOrigin'] = $resourceCollection['projectOrigin'];
            $insertData['projectReward'] = $resourceCollection['projectReward'];
            $insertData['language'] = $resourceCollection['language'];
            $insertData['resource_code'] = $resourceCollection['resourceCode'];
            $insertData['source'] = $resourceCollection['source'];
            $insertData['tag'] = $resourceCollection['tag'];
            resourceDB::table('resource_project')->insert($insertData);
        }

    }



    /**
    * 已认领成果数量
    */
    public function getUserResourceNum(){
        /**
         * userId              名片编号
         */
        $this->datas = $this->params;

        $this->getUserResourceNumService();
    }


    private function getUserResourceNumService(){
        
        $sql = "SELECT resource_code as resourceCode,COUNT(1) as num FROM user_resource where user_id = ".$this->datas['userId']." GROUP BY resource_code order by create_time desc";
        $res = resourceDB::query($sql);

        //查询总数
        $countsql = "SELECT COUNT(1) as num FROM user_resource where user_id = ".$this->datas['userId'];
        $countres = resourceDB::query($countsql);

        $this->returnMsg(1, '获取数据成功！', $res, $countres[0]['num']);
    }

    /**
    * 已认领成果列表（分页）
    */
    public function getUserResourcePage(){
        /**
         * userId              名片编号
         * resourceCode        资源类型简写
         * orderByType         排列顺序（1-时间倒序，2-时间正序）
         * pageNo              页码
         * pageSize            每页条数
         */
        $this->datas = $this->params;

        $this->getUserResourcePageService();
    }


    private function getUserResourcePageService(){
        $pageNo = 1;
        $pageSize = 10;
        $orderByType = 1;

        if(!empty($this->datas['orderByType'])){
            $orderByType = $this->datas['orderByType'];
        }

        if(!empty($this->datas['pageNo'])){
            $pageNo = $this->datas['pageNo'];
        }

        if(!empty($this->datas['pageSize'])){
            $pageSize = $this->datas['pageSize'];
        }

        $pageNo = ($pageNo - 1) * $pageSize;

        $sql = "SELECT * FROM user_resource where user_id = ".$this->datas['userId'];
        $countsql = "SELECT count(1) as num FROM user_resource where user_id = ".$this->datas['userId'];

        if(!empty($this->datas['resourceCode']) and $this->datas['resourceCode'] != ''){
            $sql = $sql." and resource_code = '".$this->datas['resourceCode']."'";
            $countsql = $countsql." and resource_code = '".$this->datas['resourceCode']."'";
        }

        if($orderByType == 1){
            $sql = $sql." order by year desc limit ".$pageNo.",".$pageSize;
        }else{
            $sql = $sql." order by year asc limit ".$pageNo.",".$pageSize;
        }

        $res = resourceDB::query($sql);
        $count = resourceDB::query($countsql);
        if(!empty($res)){
            foreach($res as &$value){
                //计算是否新认领
                $dayDiff = round((strtotime(date('Y-m-d h:i:s', time()))-strtotime($value['create_time']))/3600/24);
                if($dayDiff > 7){
                    $value['isNew'] = 0;
                }else{
                    $value['isNew'] = 1;
                }
                //查询资源详情
                $resourceInfo = resourceDB::table('local_resource_collection')->where('id',$value['resource_id'])->find();
                //论文：D  I   E   J   U   C
                //成果奖励:A
                //图书:B
                //专利:P
                //项目（横向，纵向）:O
                $resourceInfo;
                switch ($value['resource_code']) {
                    case "C":
                        $value['title'] = $resourceInfo['title'];
                        $value['creatorAll'] = $resourceInfo['creatorAll'];
                        $value['instituteAll'] = $resourceInfo['instituteAll'];
                        $value['keyword'] = $resourceInfo['keyword'];
                        $value['journal'] = $resourceInfo['journal'];
                        $value['year'] = $resourceInfo['year'];
                        $value['volume'] = $resourceInfo['volume'];
                        $value['issue'] = $resourceInfo['issue'];
                        $value['tag'] = $resourceInfo['tag'];
                        $value['url'] = $resourceInfo['url'];
                        break;
                    case "D":
                        $value['title'] = $resourceInfo['title'];
                        $value['creatorAll'] = $resourceInfo['creatorAll'];
                        $value['instituteAll'] = $resourceInfo['instituteAll'];
                        $value['keyword'] = $resourceInfo['keyword'];
                        $value['journal'] = $resourceInfo['journal'];
                        $value['year'] = $resourceInfo['year'];
                        $value['volume'] = $resourceInfo['volume'];
                        $value['issue'] = $resourceInfo['issue'];
                        $value['tag'] = $resourceInfo['tag'];
                        $value['url'] = $resourceInfo['url'];
                        break;
                    case "I":
                        $value['title'] = $resourceInfo['title'];
                        $value['creatorAll'] = $resourceInfo['creatorAll'];
                        $value['instituteAll'] = $resourceInfo['instituteAll'];
                        $value['keyword'] = $resourceInfo['keyword'];
                        $value['journal'] = $resourceInfo['journal'];
                        $value['year'] = $resourceInfo['year'];
                        $value['volume'] = $resourceInfo['volume'];
                        $value['issue'] = $resourceInfo['issue'];
                        $value['tag'] = $resourceInfo['tag'];
                        $value['url'] = $resourceInfo['url'];
                        break;
                    case "E":
                        $value['title'] = $resourceInfo['title'];
                        $value['creatorAll'] = $resourceInfo['creatorAll'];
                        $value['instituteAll'] = $resourceInfo['instituteAll'];
                        $value['keyword'] = $resourceInfo['keyword'];
                        $value['journal'] = $resourceInfo['journal'];
                        $value['year'] = $resourceInfo['year'];
                        $value['volume'] = $resourceInfo['volume'];
                        $value['issue'] = $resourceInfo['issue'];
                        $value['tag'] = $resourceInfo['tag'];
                        $value['url'] = $resourceInfo['url'];
                        break;
                    case "J":
                        $value['title'] = $resourceInfo['title'];
                        $value['creatorAll'] = $resourceInfo['creatorAll'];
                        $value['instituteAll'] = $resourceInfo['instituteAll'];
                        $value['keyword'] = $resourceInfo['keyword'];
                        $value['journal'] = $resourceInfo['journal'];
                        $value['year'] = $resourceInfo['year'];
                        $value['volume'] = $resourceInfo['volume'];
                        $value['issue'] = $resourceInfo['issue'];
                        $value['tag'] = $resourceInfo['tag'];
                        $value['url'] = $resourceInfo['url'];
                        break;
                    case "U":
                        $value['title'] = $resourceInfo['title'];
                        $value['creatorAll'] = $resourceInfo['creatorAll'];
                        $value['instituteAll'] = $resourceInfo['instituteAll'];
                        $value['keyword'] = $resourceInfo['keyword'];
                        $value['journal'] = $resourceInfo['journal'];
                        $value['year'] = $resourceInfo['year'];
                        $value['volume'] = $resourceInfo['volume'];
                        $value['issue'] = $resourceInfo['issue'];
                        $value['tag'] = $resourceInfo['tag'];
                        $value['url'] = $resourceInfo['url'];
                        break;
                    case "A":
                        $value['title'] = $resourceInfo['title'];
                        $value['allCompletedPeople'] = $resourceInfo['allCompletedPeople'];
                        $value['awardType'] = $resourceInfo['awardType'];
                        $value['awardWinningYear'] = $resourceInfo['awardWinningYear'];
                        $value['awardWinningLevel'] = $resourceInfo['awardWinningLevel'];
                        $value['tag'] = $resourceInfo['tag'];
                        $value['url'] = $resourceInfo['url'];
                        break;
                    case "B":
                        $value['title'] = $resourceInfo['title'];
                        $value['creator'] = $resourceInfo['creator'];
                        $value['year'] = $resourceInfo['year'];
                        $value['tag'] = $resourceInfo['tag'];
                        $value['url'] = $resourceInfo['url'];
                        break;
                    case "P":
                        $value['title'] = $resourceInfo['title'];
                        $value['patentName'] = $resourceInfo['patentName'];
                        $value['allInventors'] = $resourceInfo['allInventors'];
                        $value['legalState'] = $resourceInfo['legalState'];
                        $value['applicationNo'] = $resourceInfo['applicationNo'];
                        $value['patentNo'] = $resourceInfo['patentNo'];
                        $value['publicationDate'] = $resourceInfo['publicationDate'];
                        $value['tag'] = $resourceInfo['tag'];
                        $value['url'] = $resourceInfo['url'];
                        break;
                    case "O":
                        $value['title'] = $resourceInfo['title'];
                        $value['creatorAll'] = $resourceInfo['creatorAll'];
                        $value['projectNo'] = $resourceInfo['instituteAll'];
                        $value['projectFund'] = $resourceInfo['keyword'];
                        $value['projectOrigin'] = $resourceInfo['journal'];
                        $value['tag'] = $resourceInfo['tag'];
                        $value['url'] = $resourceInfo['url'];
                        break;
                    default:
                        ;
                }
            }
        }

        $this->returnMsg(1, '获取数据成功！', $res, $count[0]["num"]);
    }
   

    /**
    * 成果删除
    */
    public function delUserResource(){
        /**
         * idList              认领编号列表
         */
        $this->datas = $this->params;

        $this->delUserResourceService();
    }


    private function delUserResourceService(){
        
        $idArray = explode(',',$this->datas['idList']);
        foreach($idArray as $id){
            $delsql = "DELETE FROM  user_resource where id = ".$id;
            resourceDB::execute($delsql);
        }
        $this->returnMsg(1, '操作成功！');
    }


    /**
     * 根据id查询资源详情
     */
    public function getResourceById(){
        $this->datas = $this->params;
        try {
            $result = resourceDB::table('resource_collection')->where('id',$this->datas['id'])->find();
            if(empty($result)){
                $this->returnMsg(9, '暂无数据！');
            }

            $this->returnMsg(1, '获取数据成功！', $result);
        }catch (Exception $e){
            echo $e->getMessage();
        }
    }

}